package timestampassigner

import (
	"time"

	"github.com/project-flogo/core/activity"
	"github.com/project-flogo/core/data/coerce"
	"github.com/project-flogo/core/data/metadata"
)

func init() {
	_ = activity.Register(&Activity{}, New) //activity.Register(&Activity{}, New) to create instances using factory method 'New'
}

var activityMd = activity.ToMetadata(&Settings{}, &Input{}, &Output{})

//New optional factory method, should be used if one activity instance per configuration is desired
func New(ctx activity.InitContext) (activity.Activity, error) {

	s := &Settings{}
	err := metadata.MapToStruct(ctx.Settings(), s, true)
	if err != nil {
		return nil, err
	}

	// ctx.Logger().Debugf("Setting: %s", s.ASetting)

	act := &Activity{
		settings: *s,
	} //add aSetting to instance

	return act, nil
}

// Activity is an sample Activity that can be used as a base to create a custom activity
type Activity struct {
	settings Settings
}

// Metadata returns the activity's metadata
func (a *Activity) Metadata() *activity.Metadata {
	return activityMd
}

// Eval implements api.Activity.Eval - Logs the Message
func (a *Activity) Eval(ctx activity.Context) (done bool, err error) {

	input := &Input{}
	err = ctx.GetInputObject(input)
	if err != nil {
		return true, err
	}
	var timestamp int64
	timestampOk := false
	fieldName := a.settings.TimestampField
	if timestampField, ok := input.Data[fieldName]; ok {
		t, err := coerce.ToInt64(timestampField)
		if err == nil {
			timestampOk = true
			timestamp = t
		}
	}
	if !timestampOk {
		if a.settings.SystemDefault {
			timestamp = time.Now().UnixNano()
		}
	}

	data := map[string]DataEntry{}
	for k, v := range input.Data {
		data[k] = DataEntry{
			Value:     v,
			Timestamp: timestamp,
		}
	}

	output := &Output{
		Data: data,
	}
	err = ctx.SetOutputObject(output)
	if err != nil {
		return true, err
	}

	return true, nil
}
